#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/9  20:44
# @Author: 余浪人
# @email: yulangren520@gmail.com
import os,logging
from pathlib import Path
from apps import get_sys_url
from apps.lib.cache_sys import mysql_conf
from flask import Blueprint, current_app, json, url_for, request

# logger = logging.getLogger(__name__)  # 系统运行日志
# logging.basicConfig(level=logging.INFO, filename='system.log', filemode='a', format='%(asctime)s - %(levelname)s[line:%(lineno)d] - %(levelname)s: %(message)s')


sys_bp = Blueprint('sys_bp', __name__)

def before_request():
    setting = Path(os.path.join(get_sys_url(), 'apps/setting.json'))
    mysql = mysql_conf()
    if not current_app.config.get('SQLALCHEMY_DATABASE_URI','') and mysql:
        current_app.config.update({"SQLALCHEMY_DATABASE_URI": f"mysql+cymysql://{mysql.mysql_user}:{mysql.mysql_password}@{mysql.mysql_host}:{mysql.mysql_port}/{mysql.mysql_dbName}"})
    elif setting.exists() and (not current_app.config.get('SQLALCHEMY_DATABASE_URI','')):
        fp=setting.open('r',encoding='utf-8')
        conf = json.loads(fp.read())
        database = conf.get('database')
        db_host = database['db_host']
        db_name = database['db_name']
        db_port = database['db_port']
        db_pwd = database['db_pwd']
        db_user = database['db_user']
        current_app.config.update({"SQLALCHEMY_DATABASE_URI":f"mysql+cymysql://{db_user}:{db_pwd}@{db_host}:{db_port}/{db_name}"})
    elif request.path!=url_for('sys_bp.install') and (request.path!=url_for('sys_bp.db_connect',classify=1) and request.path!=url_for('sys_bp.db_connect',classify=2)) and not current_app.config.get('SQLALCHEMY_DATABASE_URI',''):
        return '连接数据库失败！请检查配置是否正确'
sys_bp.before_request(before_request)

from apps.control import system_view,content_view,payment_view,member_view,synthesize_view,file_view,comment_view,restrict_view,stationmaster_view,records_center_view,plugs_view,separatePage_view,user_view,install_view,static_file_html_view